package formal.tree.ergodic;

import java.util.LinkedList;
import java.util.Queue;

/**
 * @author DengYuan2
 * @create 2021-01-19 21:18
 */
public class M_513 {
    public static void main(String[] args) {
//        Integer[] a ={2,1,3};
        Integer[] a = {1, 2, 3, 4, null, 5, 6, null, null, 7,null};
        TreeNode treeNode = TreeNode.generateTree(a);
        int res = findBottomLeftValue2(treeNode);
        System.out.println(res);
    }

    /**
     * 我的写法
     * @param root
     * @return
     */
    public static int findBottomLeftValue(TreeNode root) {
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        int left=root.val;
        while (!queue.isEmpty()){
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                TreeNode poll =queue.poll();
                if (i==0){
                    left=poll.val;
                }
                if (poll.left!=null){
                    queue.offer(poll.left);
                }
                if (poll.right!=null){
                    queue.offer(poll.right);
                }
            }
        }
        return left;
    }

    /**
     * 大神-极为简单
     * 右节点先入队！！！
     * @param root
     * @return
     */
    public static int findBottomLeftValue2(TreeNode root){
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()){
            root = queue.poll();
            if (root.right!=null){
                queue.offer(root.right);
            }
            if (root.left!=null){
                queue.offer(root.left);
            }
        }
        return root.val;
    }
}
